package com.sgb.kjwl.view.ui.fragment.home;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ScaleXSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.amap.api.maps.model.AMapGestureListener;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.sdk.mobile.manager.login.NoDoubleClickListener;
import com.sgb.alimaplibrary.MarkerEntity;
import com.sgb.alimaplibrary.widget.MapMarkerView;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentLease4Binding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.sgb.kjwl.model.ZulinMenuEntity;
import com.swgk.core.view.entity.EnterpriseEditEntity;
import com.sgb.kjwl.model.entity.home.RefreshHomeNoticeEVent;
import com.sgb.kjwl.model.entity.lease.AskLeaseItemEntity;
import com.sgb.kjwl.model.entity.lease.LeaseMapEntity;
import com.sgb.kjwl.model.entity.request.LeaseHallMapFilterJson;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.swgk.core.util.ACAdminDialogUtils;
import com.sgb.kjwl.utils.DialogHelper;
import com.sgb.kjwl.view.event.ChooseAreaEvent;
import com.swgk.core.event.EventConstant;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.ui.activity.house.LeaseHallMapActivity;
import com.sgb.kjwl.view.ui.activity.lease.LeaseHallActivity2;
import com.sgb.kjwl.view.ui.activity.lease.ZulinGaodeSearchActivity;
import com.sgb.kjwl.view.ui.adapter.home.ZulinMenuAdapter;
import com.swgk.core.view.weiget.BigHomeComparyWidget;
import com.sgb.kjwl.viewmodel.home.LeaseFragment3Model;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.adapter.FragPagerAdapter;
import com.swgk.core.refresh.SuperSwipeRefreshLayout;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import com.swgk.core.base.AppLazyFragment;


/**
 * 租赁首页
 */
public class LeaseFragment3 extends AppLazyFragment {
    @Inject
    LeaseFragment3Model viewModel;
    private FragmentLease4Binding binding;
    private FragPagerAdapter pagerAdapter;
    private ArrayList<Fragment> mFragments;
    private String[] titles = {"出租", "需求", "自营", "热门"};
    private final String[] tabTitles = {"出租大厅", "需求大厅", "自营租赁", "集采竞价", "企业专项", "转让大厅"};
    private TextView textView;
    private LatLng latLng = new LatLng(0, 0); //当前使用位置经纬度
    private String mAddress;//当前使用地址
    private LeaseHallMapFilterJson filterJson = new LeaseHallMapFilterJson();
    private Bundle savedInstanceState;
    private boolean isMap = true;
    private int menuPosition = 0;//当前菜单下标

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    public static LeaseFragment3 newInstance(String type) {
        LeaseFragment3 fragment = new LeaseFragment3();
//        Bundle bundle = new Bundle();
//        bundle.putString(KEY_TYPE, type);
//        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_lease4, container, false);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        this.savedInstanceState = savedInstanceState;
        return binding.getRoot();
    }


    @Override
    protected void initView() {
        initMap(savedInstanceState);
        initSwipeRefresh();
        initAppBarLayout();
        initTabMode();
        initTypeLayout();
        binding.tvAdressSearch.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                Intent intent = new Intent(getActivity(), ZulinGaodeSearchActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivityForResult(intent, 100);
            }
        });
        binding.imgBackTop.setOnClickListener(v -> {
            ViewGroup.LayoutParams layoutParams = binding.appBarLayout.getLayoutParams();
            AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) ((CoordinatorLayout.LayoutParams) layoutParams).getBehavior();
            if (behavior != null) {
                float y = binding.recyclerMenu.getY();
                behavior.setTopAndBottomOffset((int) -y);
                binding.swipeRefresh.setEnabled(true);
            }
        });
    }

    private void initAppBarLayout() {
        binding.appBarLayout.addOnOffsetChangedListener((appBarLayout, i) -> {
            binding.swipeRefresh.setEnabled(i >= 0);
        });
        binding.appBarLayout.post(this::setAppbarDragCallback);
    }

    private void setAppbarDragCallback() {
        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) binding.appBarLayout.getLayoutParams();
        AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior();
        if (behavior != null) {
            behavior.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
                @Override
                public boolean canDrag(@NonNull AppBarLayout appBarLayout) {
                    return true;
                }
            });
        }
    }

    //清空选项数据
    private void clearText() {
        binding.tvAdressSearch.setText("");
        binding.tvType.setText("");
        binding.tvCategory.setText("");
        type = 0;
        categoryFirst = "";
        categorySecond = "";
        categorySecondName = "";
        binding.llCategory.setBackgroundResource(R.drawable.bg_e8e8e8_corners8);
    }

    private void initTypeLayout() {
        binding.tvGo.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                if (TextUtils.isEmpty(binding.tvAdressSearch.getText()) || TextUtils.isEmpty(binding.tvCategory.getText())) {
                    MToast.showToast(getActivity(), "请完整填写匹配信息");
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString("title", binding.tvAdressSearch.getText().toString());
                bundle.putString("text", binding.tvAdressSearch.getText().toString());
                bundle.putDouble("lat", (Double) binding.tvAdressSearch.getTag(R.id.tv_type));
                bundle.putDouble("lon", (Double) binding.tvAdressSearch.getTag(R.id.tv_category));
                bundle.putString("type", String.valueOf(type));
                bundle.putString("categoryFirst", categoryFirst);
                bundle.putString("categorySecond", categorySecond);
                bundle.putString("categorySecondName", categorySecondName);
                LeaseHallMapActivity.startForBundle(getActivity(), bundle);
                //跳转后清空数据
                clearText();
            }
        });
        binding.llType.setOnClickListener(v -> onShowType(viewModel.getType()));
        binding.llCategory.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                if (TextUtils.isEmpty(binding.tvType.getText())) {
                    return;
                }
                if (type == 2) {//车辆
                    if (cartypelist.size() > 0) {
                        showcarTypePop();
                    } else {
                        viewModel.getModelSelect();
                    }
                } else {
                    if (classDatas.size() != 0) {
                        if (type == 5) {//工厂
                            showFactoryTypePop();
                        } else {
                            showClassTypePop();
                        }
                    } else {
                        viewModel.getTypeModel();
                    }
                }
            }
        });
    }

    @Override
    protected void onLazyLoad() {
        viewModel.getMenu(menuPosition);//获取菜单
        viewModel.getTypeModel();
        viewModel.getCompanyTitleList("refreshHomeData"); //获取首页企业推荐

        initFragments();
        Handler handlerMap = new Handler();
        handlerMap.postDelayed(new Runnable() {
            public void run() {
                //解决首页返回的定位有延迟的情况
                resfreshMapdata();
                handlerMap.removeCallbacksAndMessages(null);
            }
        }, 3000);
    }

    private void initFragments() {
        mFragments = new ArrayList<>();
        for (int i = 0; i < titles.length; i++) {
            mFragments.add(LeaseListFragment.newInstance(i));//首页热门推荐
        }
        pagerAdapter = new FragPagerAdapter(getChildFragmentManager(), mFragments);
        binding.viewpagerF.setAdapter(pagerAdapter);
        binding.slidingTabLayout.setViewPager(binding.viewpagerF, titles);
        binding.slidingTabLayout.setCurrentTab(0);
    }

    //分类数据绑定
    public void initTabMode() {
        for (int i = 0; i < tabTitles.length; i++) {
            binding.tabMode.addTab(binding.tabMode.newTab().setText(tabTitles[i]));

        }

        binding.tabMode.setTabMode(TabLayout.MODE_SCROLLABLE);

        for (int i = 0; i < tabTitles.length; i++) {
            View view = LayoutInflater.from(requireActivity()).inflate(R.layout.item_tab_4z_menu, null, false);
            binding.tabMode.getTabAt(i).setCustomView(view);
            TextView tv = binding.tabMode.getTabAt(i).getCustomView().findViewById(R.id.tv_tabItem);
            String text = tabTitles[i];
            SpannableString spannableString = new SpannableString(text);
            //设置字体大小（相对值,单位：像素） 参数表示为默认字体宽度的多少倍
            //2.0f表示默认字体宽度的两倍，即X轴方向放大为默认字体的两倍，而高度不变
            spannableString.setSpan(new ScaleXSpan(1.3f), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            tv.setText(spannableString);
            if (i == 0) {
                tv.setSelected(true);
            }
        }
        binding.tabMode.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                TextView tv = tab.getCustomView().findViewById(R.id.tv_tabItem);
                tv.setSelected(true);
                tv.invalidate();

                if ("企业专项".equals(tabTitles[tab.getPosition()])) {
                    binding.tabMode.getTabAt(menuPosition).select();
                    if (!DialogHelper.checkLogin()) {
                        DialogHelper.showLoginDialogNew(getActivity(), EventConstant.EVENT_INTELL_PROP_FRG_JUMP, "温馨提示", "登录后可查看企业专项,去登录", "登录");
                        return;
                    } else {
                        //type类型 0个人 1企业 2团队 3组织
                        int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
                        if (type == 2 || type == 3) {
                            ACAdminDialogUtils.showACDialogNew(getActivity(), "温馨提示", "请前往个人中心切换个人或者企业身份进入企业专项", "立即前往",
                                    new ACAdminDialogUtils.DialogClick() {
                                        @Override
                                        public void dialogClick1() {
                                            EventBus.getDefault().postSticky(MenuEvent.make().setMessageTag(EventConstant.EVENT_BIG_HOME_JUMP_CENTER));
                                        }
                                    });
                        } else {
                            LeaseHallActivity2.start(getActivity(), 5, 0);
                        }
                    }

                    return;
                }

                //租赁菜单需要执行的判断处理
                if ("转让大厅".equals(tabTitles[tab.getPosition()]) || "企业专项".equals(tabTitles[tab.getPosition()])) {
                    binding.tabMode.getTabAt(menuPosition).select();
                    MToast.showToast(getActivity(), "功能开发中");
                } else {
                    //刷新数据
                    menuPosition = tab.getPosition();
                    viewModel.getMenu(menuPosition);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                TextView tv = tab.getCustomView().findViewById(R.id.tv_tabItem);
                tv.setSelected(false);
                tv.invalidate();
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    public void showMenuView(List<List<ZulinMenuEntity>> data) {
        ZulinMenuAdapter adapter = new ZulinMenuAdapter(getActivity(), data);
        adapter.setListener(entity -> onMenuItemClick(entity));
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        binding.recyclerMenu.setLayoutManager(manager);
        binding.recyclerMenu.setAdapter(adapter);
//        binding.treeIndicator.bindRecyclerView(binding.recyclerMenu);
    }

    private void onMenuItemClick(ZulinMenuEntity entity) {
        if (entity.getName().equals("机械租赁")) {
            LeaseHallActivity2.start(getActivity(), 0, 1);
//            ZulinMechanicalActivity.start(getActivity(), "1", entity.getName());
        } else if (entity.getName().equals("设备租赁")) {
            LeaseHallActivity2.start(getActivity(), 0, 2);
        } else if (entity.getName().equals("车辆租赁")) {
            LeaseHallActivity2.start(getActivity(), 0, 3);
        } else if (entity.getName().equals("房产租赁")) {
            LeaseHallActivity2.start(getActivity(), 0, 4);
        } else if (entity.getName().equals("土地租赁")) {
            LeaseHallActivity2.start(getActivity(), 0, 5);
        } else if (entity.getName().equals("工厂租赁")) {
            LeaseHallActivity2.start(getActivity(), 0, 6);
        } else if (entity.getName().equals("农机租赁")) {
            LeaseHallActivity2.start(getActivity(), 0, 7);
        } else if (entity.getName().equals("机械求租")) {
            LeaseHallActivity2.start(getActivity(), 1, 1);
        } else if (entity.getName().equals("设备求租")) {
            LeaseHallActivity2.start(getActivity(), 1, 2);
        } else if (entity.getName().equals("车辆求租")) {
            LeaseHallActivity2.start(getActivity(), 1, 3);
        } else if (entity.getName().equals("房产求租")) {
            LeaseHallActivity2.start(getActivity(), 1, 4);
        } else if (entity.getName().equals("土地求租")) {
            LeaseHallActivity2.start(getActivity(), 1, 5);
        } else if (entity.getName().equals("工厂求租")) {
            LeaseHallActivity2.start(getActivity(), 1, 6);
        } else if (entity.getName().equals("农机求租")) {
            LeaseHallActivity2.start(getActivity(), 1, 7);
        } else if (entity.getName().equals("自营机械")) {
            LeaseHallActivity2.start(getActivity(), 2, 1);
        } else if (entity.getName().equals("自营设备")) {
            LeaseHallActivity2.start(getActivity(), 2, 2);
        } else if (entity.getName().equals("自营车辆")) {
            LeaseHallActivity2.start(getActivity(), 2, 3);
        } else if (entity.getName().equals("自营房产")) {
            LeaseHallActivity2.start(getActivity(), 2, 4);
        } else if (entity.getName().equals("自营土地")) {
            LeaseHallActivity2.start(getActivity(), 2, 5);
        } else if (entity.getName().equals("自营工厂")) {
            LeaseHallActivity2.start(getActivity(), 2, 6);
        } else if (entity.getName().equals("自营农机")) {
            LeaseHallActivity2.start(getActivity(), 2, 7);
        } else if (entity.getName().equals("机械集采")) {
            LeaseHallActivity2.start(getActivity(), 3, 1);
        } else if (entity.getName().equals("设备集采")) {
            LeaseHallActivity2.start(getActivity(), 3, 2);
        } else if (entity.getName().equals("机械竞价")) {
            LeaseHallActivity2.start(getActivity(), 4, 1);
        } else if (entity.getName().equals("设备竞价")) {
            LeaseHallActivity2.start(getActivity(), 4, 2);
            //        } else if (entity.getName().equals("出租大厅")) {
//            LeaseHallActivity2.start(getActivity());
//        } else if (entity.getName().equals("需求大厅")) {
//            AskLeaseActivity.start(getActivity());
//        } else if (entity.getName().equals("地图查找")) {
//            LeaseHallMapActivity.start(getActivity());
//        } else if (entity.getName().equals("集采租赁")) {
////                    XuFangFaQiActivity.start(getActivity(), "1");
//            AskLeaseActivity.start(getActivity(), 2);
//        } else if (entity.getName().equals("竞价租赁")) {
//            AskLeaseActivity.start(getActivity(), 1);
        } else {
            MToast.showToast(getActivity(), "功能开发中");
        }
    }

    private void initSwipeRefresh() {
        binding.swipeRefresh.setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {
            @Override
            public void onRefresh() {
                clearText();
                textView.setText("正在刷新");
                viewModel.getMenu(menuPosition);
                binding.swipeRefresh.setRefreshing(false);//刷新完成,隐藏刷新进度条
                LeaseListFragment fragment = (LeaseListFragment) mFragments.get(binding.slidingTabLayout.getCurrentTab());
                fragment.onRefresh();
                viewModel.getLeaseMapSearch(filterJson);
            }

            @Override
            public void onPullDistance(int distance) {

            }

            @Override
            public void onPullEnable(boolean enable) {
                textView.setText(enable ? "释放立即刷新" : "下拉刷新");
            }
        });

        binding.swipeRefresh.setHeaderView(createHeaderView());
    }

    private View createHeaderView() {
        @SuppressLint("InflateParams")
        View headerView = LayoutInflater.from(binding.swipeRefresh.getContext()).inflate(R.layout.super_swipe_refresh_head, null);
        ProgressBar progressBar = headerView.findViewById(R.id.pb_view);
        textView = headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        progressBar.setVisibility(View.GONE);
        return headerView;
    }

    //是否启用下拉刷新,用于解决子界面RecyclerView下拉刷新的冲突
    public void setEnabled(boolean isEnabled) {
        binding.swipeRefresh.setEnabled(isEnabled);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(ChooseAreaEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CHOOSE_AERA) {
            if (mFragments != null && mFragments.get(binding.slidingTabLayout.getCurrentTab()) instanceof LeaseListFragment) {
                LeaseListFragment fragment = (LeaseListFragment) mFragments.get(binding.slidingTabLayout.getCurrentTab());
                fragment.onRefresh();
            }
            resfreshMapdata();
        }

    }

    /**
     * 用户切换身份后通知大首页刷新数据
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(RefreshHomeNoticeEVent event) {
        if (event.getMsgNoticeTag() == EventConstant.EVENT_NOTICE_REFRESH_HOME) {
            if(bigHomeCompary==null)return;
            bigHomeCompary.unInit();
            //获取首页企业推荐
            viewModel.getCompanyTitleList("EventConstant.EVENT_NOTICE_REFRESH_HOME");
        }
    }

    private void resfreshMapdata() {
        //当省份切换后刷新地图数据
        if (viewModel.repertory.getIsLocal()) {
            //经度
            filterJson.setLatitude("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, ""))
                    ? viewModel.repertory.getLatitude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, ""));
            //纬度
            filterJson.setLongitude("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, ""))
                    ? viewModel.repertory.getLongititude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, ""));
        } else {
            //经度
            filterJson.setLongitude(viewModel.repertory.getLongititude());
            //纬度
            filterJson.setLatitude(viewModel.repertory.getLatitude());
        }
        if (!TextUtils.isEmpty(filterJson.getLatitude()) && !TextUtils.isEmpty(filterJson.getLongitude())) {
            latLng = new LatLng(Double.parseDouble(filterJson.getLatitude()), Double.parseDouble(filterJson.getLongitude()));
            binding.mMapView.zoomToSpan(latLng);
            viewModel.getLeaseMapSearch(filterJson);
            SharedPreferenceUtil.getInstance().saveData("Lease_Latitude", filterJson.getLatitude());
            SharedPreferenceUtil.getInstance().saveData("Lease_Longitude", filterJson.getLongitude());
        }

    }

//    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
//    public void onEvent(LoginEvent event) {
//        if (event.getMessageTag() == EventConstant.EVENT_LOGIN || event.getMessageTag() == EventConstant.EVENT_LOGIN_OUT) {
//            if (binding != null && binding.leaseRelease != null){
//                binding.leaseRelease.initPhoneAndCode();
//            }
//        }
//    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    //初始化地图
    private void initMap(Bundle savedInstanceState) {
//        binding.mMapView.getMap().getUiSettings().setAllGesturesEnabled(false);
        binding.mMapView.getMap().setMyLocationStyle(null);
        binding.mMapView.getMap().setMyLocationEnabled(false);
        binding.mMapView.getMap().getUiSettings().setMyLocationButtonEnabled(false);
        binding.mMapView.initMap(savedInstanceState, getLifecycle(), 4, new MapMarkerView.CallBack() {
            @Override
            public void onMarkerClick(int pos, String title) {
            }

            @Override
            public void onLocation(Double Lat, Double Log, String address) {
//                binding.mMapView.getMap().setMyLocationEnabled(false);
//                latLng = new LatLng(Lat, Log);
//                binding.mMapView.zoomToSpan(latLng);
//                mAddress = address;
//                binding.tvAdressCurr.setText(address);
//                filterJson.setLatitude(Lat);
//                filterJson.setLongitude(Log);
//                viewModel.getLeaseMapSearch(filterJson);
//                binding.mMapView.mapMarkerTools.setMyLocation(Lat, Log, R.mipmap.location_red);
            }

        });
        //导航箭头定位的小图标，这里自定义一张图片
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.strokeWidth(0f);// 设置圆形的边框粗细
        myLocationStyle.anchor(0.5f, 0.7f);
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色  这样圆圈就没有了，看不到了
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        myLocationStyle.showMyLocation(false);
        binding.mMapView.getMap().setMyLocationStyle(myLocationStyle);
        binding.mMapView.getMap().setOnMapClickListener(latLng1 -> toMapSearch());
        binding.mMapView.getMap().setAMapGestureListener(new AMapGestureListener() {
            @Override
            public void onDoubleTap(float v, float v1) {
            }

            @Override
            public void onSingleTap(float v, float v1) {
            }

            @Override
            public void onFling(float v, float v1) {
            }

            @Override
            public void onScroll(float v, float v1) {
                toMapSearch();
            }

            @Override
            public void onLongPress(float v, float v1) {
            }

            @Override
            public void onDown(float v, float v1) {
            }

            @Override
            public void onUp(float v, float v1) {
            }

            @Override
            public void onMapStable() {
            }
        });
    }


    private void toMapSearch() {
        if (isMap) {
            isMap = false;
            try {
                Bundle bundle = new Bundle();
                bundle.putString("title", binding.tvAdressSearch.getText().toString());
                bundle.putString("text", binding.tvAdressSearch.getText().toString());
                bundle.putDouble("lat", (Double) binding.tvAdressSearch.getTag(R.id.tv_type));
                bundle.putDouble("lon", (Double) binding.tvAdressSearch.getTag(R.id.tv_category));
                bundle.putString("type", TextUtils.isEmpty(binding.tvType.getText()) ? "" : String.valueOf(type));
                bundle.putString("categoryFirst", categoryFirst);
                bundle.putString("categorySecond", categorySecond);
                bundle.putString("categorySecondName", categorySecondName);
                LeaseHallMapActivity.startForBundle(getActivity(), bundle);
            } catch (Exception ex) {
                Bundle bundle = new Bundle();
                bundle.putString("title", mAddress);
                bundle.putString("text", mAddress);
                bundle.putDouble("lat", latLng.latitude);
                bundle.putDouble("lon", latLng.longitude);
                bundle.putString("type", TextUtils.isEmpty(binding.tvType.getText()) ? "" : String.valueOf(type));
                bundle.putString("categoryFirst", categoryFirst);
                bundle.putString("categorySecond", categorySecond);
                bundle.putString("categorySecondName", categorySecondName);
                LeaseHallMapActivity.startForBundle(getActivity(), bundle);
            }

            clearText();
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    //解决短时间重复移动地图的重复跳转问题
                    isMap = true;
                    handler.removeCallbacksAndMessages(null);
                }
            }, 2000);
            return;
        }
    }

    public void showMapMark(List<LeaseMapEntity> datas) {
        if (datas == null || datas.size() == 0) {
            return;
        }

        try {
            List<MarkerEntity> markerEntityList = new ArrayList<>();
            for (int i = 0; i < datas.size(); i++) {
                LeaseMapEntity entity = datas.get(i);
                LatLng latLng = new LatLng(Double.parseDouble(entity.getLatitude()), Double.parseDouble(entity.getLongitude()));
                int icon = R.mipmap.ic_map_overlay_lease;
                markerEntityList.add(new MarkerEntity(latLng, icon, entity.getNo()));
            }
            binding.mMapView.setMarkerData(markerEntityList);
            //因为首页经纬度获取有延时，所有需刷新数据后重置位置
            if (viewModel.repertory.getIsLocal()) {
                //经度
                filterJson.setLatitude("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, ""))
                        ? viewModel.repertory.getLatitude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, ""));
                //纬度
                filterJson.setLongitude("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, ""))
                        ? viewModel.repertory.getLongititude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, ""));
            } else {
                //经度
                filterJson.setLongitude(viewModel.repertory.getLongititude());
                //纬度
                filterJson.setLatitude(viewModel.repertory.getLatitude());
            }
            if (!TextUtils.isEmpty(filterJson.getLatitude()) && !TextUtils.isEmpty(filterJson.getLongitude())) {
                latLng = new LatLng(Double.parseDouble(filterJson.getLatitude()), Double.parseDouble(filterJson.getLongitude()));
                binding.mMapView.zoomToSpan(latLng);
                SharedPreferenceUtil.getInstance().saveData("Lease_Latitude", filterJson.getLatitude());
                SharedPreferenceUtil.getInstance().saveData("Lease_Longitude", filterJson.getLongitude());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private List<PickSelectEntity> classDatas;
    private List<List<PickSelectEntity>> typeDatas;
    private List<AskLeaseItemEntity<List<AskLeaseItemEntity<List<AskLeaseItemEntity>>>>> categoryList;
    private ArrayList<PickSelectEntity> cartypelist = new ArrayList<>();//车辆类型列表
    private int type = 0;
    private String categoryFirst = "";
    private String categorySecond = "";
    private String categorySecondName = "";

    //类型集合
    public void showTypeView(List<AskLeaseItemEntity<List<AskLeaseItemEntity<List<AskLeaseItemEntity>>>>> data) {
        this.categoryList = data;
        classDatas = new ArrayList<>();
        typeDatas = new ArrayList<>();
        if (data == null || data.size() == 0) {
            return;
        }
        for (AskLeaseItemEntity<List<AskLeaseItemEntity>> l : data.get(type).getChildren()) {
            PickSelectEntity entity = new PickSelectEntity();
            entity.setNo(l.getNo());
            entity.setProjectscale(l.getName());
            classDatas.add(entity);
            List<PickSelectEntity> childList = new ArrayList<>();
            for (AskLeaseItemEntity ll : l.getChildren()) {
                PickSelectEntity child = new PickSelectEntity();
                child.setNo(ll.getNo());
                child.setProjectscale(ll.getName());
                childList.add(child);
            }
            typeDatas.add(childList);
        }
    }

    //分类选择器
    private void onShowType(List<DictEntity3> typeList) {
        OptionsPickerView build = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            String content = typeList.get(options1).getName();
            String no = typeList.get(options1).getId();
            binding.tvType.setText(content);
            binding.tvCategory.setText("");
            binding.llCategory.setBackgroundResource(R.drawable.bg_f5f5f5_corners8);
            categoryFirst = "";
            categorySecond = "";
            type = Integer.parseInt(no);
            showTypeView(categoryList);
        }).setCancelColor(ContextCompat.getColor(getActivity(), R.color.color_666666)).build();
        build.setPicker(typeList);
        build.setSelectOptions(0);
        build.setTitleText("请选择分类");
        build.show();
    }

    //类型
    private void showClassTypePop() {
        if (classDatas == null || classDatas.size() == 0 || typeDatas == null || typeDatas.size() == 0) {
            MToast.showToast(getActivity(), "类型获取失败");
            return;
        }
        OptionsPickerView businessOption = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            String className = classDatas.get(options1).getProjectscale();
            categoryFirst = classDatas.get(options1).getNo();
            binding.tvCategory.setText(className);
            //二级类别
            if (typeDatas.size() >= 0 && null != typeDatas.get(options1) && typeDatas.get(options1).size() > 0) {
                String typeName = typeDatas.get(options1).get(options2).getProjectscale();
                categorySecond = typeDatas.get(options1).get(options2).getNo();
                categorySecondName = typeName;
                binding.tvCategory.setText(className + "/" + typeName);
            }

        }).setCancelColor(ContextCompat.getColor(getActivity(), R.color.color_666666)).build();
        businessOption.setPicker(classDatas, typeDatas);
        businessOption.setSelectOptions(0);
        businessOption.setTitleText("请选择类型");
        businessOption.show();
    }

    // 工厂分类的选择
    private void showFactoryTypePop() {
        if (classDatas == null || classDatas.size() == 0) {
            MToast.showToast(getActivity(), "工厂分类获取失败");
            return;
        }
        OptionsPickerView businessOption = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            binding.tvCategory.setText(classDatas.get(options1).getPickerViewText());
            categoryFirst = classDatas.get(options1).getNo();
        }).build();
        businessOption.setPicker(classDatas);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    // 车辆类型的选择
    private void showcarTypePop() {
        if (cartypelist == null || cartypelist.size() == 0) {
            MToast.showToast(getActivity(), "车型获取失败");
            return;
        }
        OptionsPickerView businessOption = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            String classNamec = cartypelist.get(options1).getProjectscale();
            binding.tvCategory.setText(classNamec);
            categoryFirst = cartypelist.get(options1).getNo();
        }).build();
        businessOption.setPicker(cartypelist);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    //车辆类型数据列表
    public void showCarTypeView(List<DictEntity3> data) {
        for (int i = 0; i < data.size(); i++) {
            PickSelectEntity entity = new PickSelectEntity();
            entity.setNo(data.get(i).getId());
            entity.setProjectscale(data.get(i).getName());
            cartypelist.add(entity);
        }

    }

    /**
     * 初始化首页企业推荐界面
     */
    public void initCompanyTitle(List<EnterpriseEditEntity> data) {
        if (binding == null) return;
        vsCompany = binding.vsCompany.getViewStub();
        if (vsCompany != null)
            vsCompany.inflate();
        if (vsCompany != null) {
            inflatedCompany = binding.getRoot().findViewById(R.id.inflatedCompany);
            bigHomeCompary = new BigHomeComparyWidget(this, inflatedCompany);
        }
        if (bigHomeCompary != null) {
            bigHomeCompary.unInit();
        }
        if (data == null || data.size() == 0) return;
        bigHomeCompary.initData(data);
        boolean isType = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.DisplaySettingsType, true);
        boolean isQY = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.DisplaySettingsQY, true);
        bigHomeCompary.setIsAotu(isType, isQY);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == 100) {
            if (data != null) {
                String address = data.getStringExtra("text");
                double lat = data.getDoubleExtra("lat", 0);
                double lon = data.getDoubleExtra("lon", 0);
                //临时保存经纬度和地址
                binding.tvAdressSearch.setText(address);
                binding.tvAdressSearch.setTag(R.id.tv_type, lat);
                binding.tvAdressSearch.setTag(R.id.tv_category, lon);
            }
        }
    }

}

